-- daily_task
-- Created by chengb Sep/11/2015
-- 成就：完成日常任务

-- 内部函数声明
local whenDailyTaskFinish;

-- 注册日常任务完成的回调
EventMgr.register("game_achievement/daily_task", event.DAILY_TASK_FINISH, function(args)
    whenDailyTaskFinish(args);
end);

-- 注册日常任务完成的回调
whenDailyTaskFinish = function(args)
    -- 获取已完成过的日常任务
    local taskHistory = ME.user.dbase:query("daily_task_history", {});
    local count = #taskHistory;
    
    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end
        
        if GameAchievementM.getProgress(id) >= count then
            -- 进度没有变化
            return false;
        end 
               
        return true;
    end
    
    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("daily_task");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.setProgress(id, count);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg  = config["rule_arg"];
        local progress = config["progress"];
        local desc     = config["desc"];
        
        desc = string.gsub(desc, "{0}", progress);

        return desc;
    end,
};